# -*- coding: utf-8 -*-
'''
利用svm进行手写字符识别
'''

import os
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report


testf = r'F:\Github\MachineLearningInAction\svm\data\testDigits'
test_files = os.listdir(testf)
trainf = r'F:\Github\MachineLearningInAction\svm\data\trainingDigits'
training_files = os.listdir(trainf)

def img2vector(filename):
    vect = np.zeros((1,1024))
    fr = open(filename)
    for i in range(32):
        line = fr.readline()
        for j in range(32):
            vect[0,32*i+j] = int(line[j])
    fr.close()
    return vect

def getdata(filelist, DigitsName):
    labels = []
    m = len(filelist)
    Mat = np.zeros((m,1024))
    for i in range(m):
        fileName = '.\\data\\'+DigitsName+'\\' + filelist[i]
        labels.append(filelist[i].split('_')[0])
        Mat[i,:] = img2vector(fileName)
    return labels, Mat

y_train, X_train = getdata(training_files, 'trainingDigits')
y_test, X_test = getdata(test_files, 'testDigits')

pipeline = Pipeline([('clf', SVC(kernel='rbf', gamma=0.01, C=100))])

parameters = {
'clf__gamma': (0.01, 0.03, 0.1, 0.3, 1),
'clf__C': (0.1, 0.3, 1, 3, 10, 30),
}

if __name__ == '__main__':
    grid_search = GridSearchCV(pipeline, parameters, n_jobs=2,
                               verbose=1, scoring='accuracy')
    grid_search.fit(X_train[:10000], y_train[:10000])
    
    print('Best score: %0.3f' % grid_search.best_score_)
    print('Best parameters set:')
    best_parameters = grid_search.best_estimator_.get_params()
    
    for param_name in sorted(parameters.keys()):
        print('\t%s: %r' % (param_name,
    best_parameters[param_name]))
    predictions = grid_search.predict(X_test)
    
    print(classification_report(y_test, predictions))
    
#Best score: 0.967
#Best parameters set:
#        clf__C: 1
#        clf__gamma: 0.01
#             precision    recall  f1-score   support
#
#          0       1.00      1.00      1.00        87
#          1       0.99      0.99      0.99        97
#          2       0.99      0.99      0.99        92
#          3       1.00      0.95      0.98        85
#          4       0.99      0.99      0.99       114
#          5       0.99      1.00      1.00       108
#          6       0.99      0.99      0.99        87
#          7       0.99      1.00      0.99        96
#          8       0.99      0.98      0.98        91
#          9       0.97      1.00      0.98        89
#
#avg / total       0.99      0.99      0.99       946





